/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        if (l1->val == 0 && l1->next == nullptr)return l2;
        else if (l2->val == 0 && l2->next == nullptr)return l1;
        int digit = l1->val + l2->val, carry = digit / 10;
        digit %= 10;
        ListNode* head = new ListNode(digit);
        ListNode* cur = head;
        l1 = l1->next, l2 = l2->next;
        while (l1 != nullptr && l2 != nullptr)
        {
            digit = l1->val + l2->val + carry;
            carry = digit / 10;
            digit %= 10;
            cur->next = new ListNode(digit);
            l1 = l1->next, l2 = l2->next, cur = cur->next;
        }

        while (l1 != nullptr)
        {
            digit = l1->val + carry;
            carry = digit / 10;
            digit %= 10;
            cur->next = new ListNode(digit);
            l1 = l1->next, cur = cur->next;
        }
        while (l2 != nullptr)
        {
            digit = l2->val + carry;
            carry = digit / 10;
            digit %= 10;
            cur->next = new ListNode(digit);
            l2 = l2->next, cur = cur->next;
        }
        if (carry != 0)cur->next = new ListNode(carry);

        return head;

    }
};